//
//  NetworkTools.swift
//  AFN封装Swift 1
//
//  Created by songhuipan on 16/4/17.
//  Copyright © 2016年 songhuipan. All rights reserved.
//

import UIKit
import AFNetworking
/// 网络请求方法枚举
///
/// - POST: POST请求
/// - GET:  GET请求
enum httpMethod :String {
    
    case POST = "POST"
    
    case GET = "GET"
    
}
class NetworkTools: AFHTTPSessionManager {
    
    static let sharedTools:NetworkTools = {
        
        let tool = NetworkTools()
        
        // 设置反序列化数据格式，系统会自动将oc 中的NSSet类型转化成Set 类型
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
}
// MARK:oauth相关方法
extension NetworkTools {
    
    ///extension中不可以定义存贮值属性，可以定义计算型属性
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthUrl: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
//        print(NSURL(string: urlString)!)
        
        return NSURL(string: urlString)!
        
    }
}
// MARK:网络请求的相关方法
extension NetworkTools {
    
      func loadData(method:httpMethod ,urlString:String ,params:AnyObject? ,finish:finishCallback){
        
        // 定义成功后的回调
        let success = {(task:NSURLSessionDataTask, responseObject:AnyObject?) -> Void in
            
            finish(responseObject: responseObject, error: nil)
            
        }
        
        let failure = {(task:NSURLSessionDataTask?, error:NSError) -> Void in
            
            finish(responseObject: nil, error: error)

        }
        
        if method == .POST {
            // 测试响应数据格式
//            responseSerializer = AFHTTPResponseSerializer()
            
            self.POST(urlString, parameters: params, progress: nil, success: success, failure: failure)
            
        }else {
            
            self.GET(urlString, parameters: params, progress: nil, success: success, failure: failure)
        }
    }
    func loadStatus(accessToken:String, since_id: Int64, max_id: Int64,finish:finishCallback) {
        // 请求url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // 请求参数
        let params = [
            "access_token": accessToken,
            "since_id": "\(since_id)",
            "max_id": "\(max_id)"
        ]
        loadData(httpMethod.GET, urlString: urlString, params: params) { (responseObject, error) -> () in
            
            finish(responseObject: responseObject, error: error)
        }
        
    }
}










